/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.learn.learn_view.command;
import java.awt.Shape;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.model.disc.fem.FemModel;
import br.ufmg.dees.insane.ui.rich.learn.learn_view.ExtensionFileFilter;
import br.ufmg.dees.insane.ui.rich.learn.learn_view.LearnInterface;
import br.ufmg.dees.insane.ui.rich.learn.learn_view.ModelToPDF;

/**
 * @author Fonseca, Flavio & Pitangueira, Roque
 * @since June 2004
 * @see gui.command.Command
 */
public class ExportPDFCommand implements Command {
    
    private LearnInterface parent;
	private JFileChooser fileChooser = new JFileChooser();
    private ExtensionFileFilter filter = new ExtensionFileFilter(new String[]{"pdf"}, "PDF Files");
	private boolean validFile;
	private String drawingFile;
	private FemModel model;
//*****************************************************************************
	
    /**
     * Creates new ExportPDFCommand
     *
     * @see gui.command.Command#execute()
     * @param parent The JFrame parent.
     */
    public ExportPDFCommand(JFrame parent) {
        this.parent = (LearnInterface)parent;
		fileChooser.setFileFilter(filter);
    }
	
//*****************************************************************************
	
	/**
     * Calls the file chooser and generates a PDF file.
     *
     * @see gui.command.Command#execute()
     */
    public void execute() {
		
		validFile = false;
		while (!validFile) {
			
			fileChooser.setDialogTitle("Export PDF");
			int retVal = fileChooser.showDialog(parent, "Export");
			if (retVal == JFileChooser.APPROVE_OPTION) {
				
				//Getting the file name
				String s = fileChooser.getSelectedFile().getName();
				
				//Getting the file extension
				String ext = new String();
				int i = s.lastIndexOf('.');
				if (i > 0 &&  i < s.length() - 1) {
					ext = s.substring(i+1).toLowerCase();
				}
				
				//Comparing the extension
				if (!ext.equals("pdf")) {
					s = s + ".pdf";
					File file = fileChooser.getSelectedFile();
					
					//Changing the file in case of no good extensions
					fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
				}
				
				//Checks if the file exists
				if (fileChooser.getSelectedFile().exists()){
						int value = 10;
						value = JOptionPane.showConfirmDialog(parent,
						"File \"" + fileChooser.getSelectedFile().getPath() + "\" exists.\nDo you want to replace it?",
						"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
						if (value == JOptionPane.YES_OPTION){
							validFile = true;
						}
				}
				else {
					//validFile = true;
				}
			}
			else return;
		}
		
		try {
			model = parent.getModel();
			this.exportDrawing();
			ModelToPDF conv = new ModelToPDF(parent, drawingFile);
			conv.setModel(model);
			conv.convertToPDF(fileChooser.getSelectedFile());
		} catch (NullPointerException e) {
			parent.addOutputText("ERROR - Could not export PDF file.");
		} catch (Exception e) {
			parent.addOutputText("ERROR - Could not export PDF file.");
		}
		validFile = false;
	}
	
//*****************************************************************************
	
    public void undo() {}
	
//*****************************************************************************
	
    public void redo() {}
    
//*****************************************************************************
	
	public void exportDrawing() {
		
		boolean saveGrid = parent.getView().getViewState().isGridOn();
		boolean saveSnap = parent.getView().getViewState().isSnapOn();
		Shape saveShape = parent.getView().getDrawingArea().getShape();
		parent.getView().getDrawingArea().setGrid(false);
		parent.getView().getDrawingArea().setSnap(false);
		parent.getView().getDrawingArea().setShape(null);
		Command cmd = new FitCommand(parent);
		cmd.execute();
		
		File jpgFile = new File("drawingFile.jpg");
		
		try {
			jpgFile = File.createTempFile("drawing", "jpg");
			jpgFile.delete();
		}catch (Exception e) {}
		
		jpgFile.deleteOnExit();
		drawingFile = jpgFile.getAbsolutePath();
		
		Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
		ImageWriter writer = (ImageWriter)writers.next();
		
		try{
			ImageOutputStream ios = ImageIO.createImageOutputStream(jpgFile);
			writer.setOutput(ios);
			//getting and writing the buffered image in the output stream
			writer.write(parent.getView().getDrawingArea().getImage());
		} catch (IllegalArgumentException e) {
			System.out.println("One of the arguments to write image is null");
			e.printStackTrace();
		} catch (IOException ie) {
			System.out.println("Exception occured in I/O");
			ie.printStackTrace();
		}
		
		parent.getView().getDrawingArea().setGrid(saveGrid);
		parent.getView().getDrawingArea().setSnap(saveSnap);
		parent.getView().getDrawingArea().setShape(saveShape);
		parent.getView().getDrawingArea().repaint();
		cmd = new LastZoomCommand(parent);
		cmd.execute();
	}
	
//*****************************************************************************
}
